﻿using System;
using System.Data;
using System.Data.Common;

namespace Vbyte.SharpOrm
{
    public static partial class OrmHelper
    {
        #region 统计
        /// <summary>
        /// 获取相关实例的总记录条数
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <returns></returns>
        public static long GetTotalRecord<T>(this TableEntry SqlTableEntry)
        {
            return GetTotalRecord(SqlTableEntry, null);
        }

        /// <summary>
        /// 使用已打开的共享连接，获取相关实例的总记录条数。
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <param name="SharedOpenConnection">已打开的共享数据库连接，只使用不关闭及销毁。</param>
        /// <param name="selectCmd">已构建的选取数据命令参数</param>
        /// <returns></returns>
        internal static long GetTotalRecord(this TableEntry SqlTableEntry, DbConnection SharedOpenConnection, DbCommand selectCmd)
        {
            long total = 0;

            DbCommand cmd = (selectCmd != null) ? selectCmd : GeneratorDbCommand(SqlTableEntry, SQLRowCommandType.Select);

            string sql = cmd.CommandText;
            sql = "Select count(*) " + sql.Substring(sql.IndexOf(" from ", StringComparison.InvariantCultureIgnoreCase));

            //Select {FieldsList} from {Table} {TableLINK} {Condition} {GroupBy} {OrderBy}
            int groupIdx = sql.LastIndexOf("Group By", StringComparison.InvariantCultureIgnoreCase);
            if (groupIdx != -1)
            {
                sql = sql.Substring(0, groupIdx);
            }
            int orderIdx = sql.LastIndexOf("Order By", StringComparison.InvariantCultureIgnoreCase);
            if (orderIdx != -1)
            {
                sql = sql.Substring(0, orderIdx);
            }

            cmd.CommandText = sql;
            //#region 清空旧的参数设置，除实例绑定属性外
            //string[] propBinds = GetInstanceBind<T>(SqlTableEntry);
            //foreach (DbParameter p in cmd.Parameters)
            //{
            //    if (!StringArrayContains(propBinds, p.ParameterName))
            //    {
            //        cmd.Parameters.Remove(p);
            //    }
            //}
            //#endregion

            if (SharedOpenConnection != null)
            {
                cmd.Connection = SharedOpenConnection;
                if (SharedOpenConnection.State == ConnectionState.Closed)
                {
                    SharedOpenConnection.Open();
                }
            }
            else
            {
                cmd.Connection = new AdoNetAdapter(SqlTableEntry).GetDbConnection();
                cmd.Connection.Open();
            }
            object result = cmd.ExecuteScalar();
            if (result != null) total = Convert.ToInt64(result);

            //不使用共享连接，临时打开了数据操作
            if (SharedOpenConnection == null)
            {
                cmd.Connection.Close();
                cmd.Connection.Dispose();
            }

            cmd.Dispose();
            return total;

        }

        /// <summary>
        /// 使用已打开的共享连接，获取相关实例的总记录条数。
        /// </summary>
        /// <param name="SqlTableEntry">表映射实例</param>
        /// <param name="SharedOpenConnection">已打开的共享数据库连接，只使用不关闭及销毁。</param>
        /// <returns></returns>
        public static long GetTotalRecord(this TableEntry SqlTableEntry, DbConnection SharedOpenConnection)
        {
            return GetTotalRecord(SqlTableEntry, SharedOpenConnection, null);
        }

        #endregion
	}
}
